package com.healthcloud.controller;

import com.healthcloud.entity.MinioUpload;
import com.healthcloud.entity.MinioUploadVo;
import com.healthcloud.entity.MsgVo;
import com.healthcloud.service.minio.MinioUploadService;
import com.healthcloud.utils.ApiRes;
import com.healthcloud.utils.PageParam;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by macro on 2019/12/25.
 */
@Api(tags = "MinioController", description = "MinIO对象存储管理")
@Controller
@RequestMapping("/minio")
public class MinioController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinioController.class);
    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;

    @Autowired
    private MinioUploadService minioUploadService;

    @ApiOperation("文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes upload(@RequestParam("file") MultipartFile file,
                         @RequestParam(required = false, value = "remark") String remark) {
        try {
            //创建一个MinIO的Java客户端
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            boolean isExist = minioClient.bucketExists(BUCKET_NAME);
            if (isExist) {
                LOGGER.info("存储桶已经存在！");
            } else {
                //创建存储桶并设置只读权限
                minioClient.makeBucket(BUCKET_NAME);
                minioClient.setBucketPolicy(BUCKET_NAME, "*.*", PolicyType.READ_ONLY);
            }
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 设置存储对象名称
            String objectName = sdf.format(new Date()) + "/" + filename;
            // 使用putObject上传一个文件到存储桶中
            minioClient.putObject(BUCKET_NAME, objectName, file.getInputStream(), file.getContentType());
            LOGGER.info("文件上传成功!");
            MinioUpload minioUploadDto = new MinioUpload();
            minioUploadDto.setName(filename);
            minioUploadDto.setUrl(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName);
            minioUploadDto.setRemark(remark);
            minioUploadService.saveMinio(minioUploadDto);
            return ApiRes.success(minioUploadDto);
        } catch (Exception e) {
            LOGGER.info("上传发生错误: {}！", e.getMessage());
        }
        return ApiRes.failure();
    }

    /**
     * 跳转至文件存储列表页
     * @return
     */
    @ApiOperation(value = "跳转至文件存储列表页")
    @GetMapping("/page")
    public String minioUpload() {
        return "bus/minio/minioUpload";
    }

    /**
     * 获取存储文件列表数据
     * @param vo 查询参数
     * @param pageParam 分页参数
     * @return
     */
    @ApiOperation("获取存储文件列表")
//    @RequiresPermissions("minioUpload:list")
    @PostMapping("/list")
    @ResponseBody
    public MsgVo list(MinioUploadVo vo, @ModelAttribute("pageParam")PageParam pageParam) {

        List<MinioUpload> list = minioUploadService.queryMinio(vo, pageParam);
        int count = minioUploadService.countMinio(vo);
        return new MsgVo(list, count, count,pageParam.getsEcho());
    }

    /**
     * 删除存储文件记录
     */
    @ApiOperation("删除存储文件记录")
    @PostMapping("/delete")
//    @RequiresPermissions("minioUpload:delete")
    @ResponseBody
    public ApiRes delete(Integer[] ids) {
        minioUploadService.deleteBatch(ids);
        return ApiRes.SUCCESS;
    }

    /**
     * 跳转存储文件新增页面
     */
    @ApiOperation("跳转存储文件新增页面")
    @GetMapping("/save")
//    @RequiresPermissions("minioUpload:save")
    public String save() {
        return "bus/minio/addMinioUpload";
    }
}
